<template>
  <div class="app-container">
    <el-table
      v-loadMore="loadMore"
      :height="tableConfig.height"
      :data="tableData"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="爬虫模板" prop="WebMagic" width="160" />
      <el-table-column label="成功任务数" prop="SuccessPageCount" width="120" />
      <el-table-column label="失败任务数" prop="LeftPageCount" width="120" />
      <el-table-column label="总的任务数" prop="TotalPageCount" width="120" />

      <el-table-column
        label="任务状态"
        prop="Status"
        :show-overflow-tooltip="true"
        width="150"
      />

      <el-table-column
        label="开始时间"
        align="center"
        prop="StartTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="任务名称" prop="Name" width="150" />
      <el-table-column label="线程个数" prop="Thread" width="100" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-popconfirm
            title="确认要停止任务吗？"
            @confirm="confirmStop(scope.row)"
          >
            <el-button
              slot="reference"
              size="mini"
              type="warning"
              icon="el-icon-circle-check"
              >停止</el-button
            >
          </el-popconfirm>
          <el-popconfirm
            title="确认要开始任务吗？"
            @confirm="confirmStart(scope.row)"
          >
            <el-button
              slot="reference"
              size="mini"
              type="success"
              icon="el-icon-circle-check"
              >开始</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    /> -->
  </div>
</template>

<script>
import { getState, updataState } from '@/api/spider/state'

export default {
  name: 'Role',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      roleList: [],
      tableData: [], // 当前显示的数据
      pageNum: 1, // 当前页数
      pageSize: 10, // 一次性展示多少条数据

      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 查询参数
      queryParams: {
        type: 'read',
        mbean: 'WebMagic:*',
        config: {
          ignoreErrors: true
        }
      },
      tableConfig: {
        height: window.innerHeight - 159
      },
      // 表单参数
      form: {},
      configForm: {},
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 表单校验
      rules: {},
      spiderName: '',
      selection: []
    }
  },
  created() {
    this.getList()
    window.addEventListener('resize', this.getHeight)
  },
  destroyed() {
    window.removeEventListener('resize', this.getHeight)
  },
  methods: {
    loadMore() {
      if (this.pageNum * this.pageSize < this.roleList.length) {
        this.pageNum++
        this.tableData = this.roleList.slice(0, this.pageNum * this.pageSize)
      } else {
        this.tableData = this.roleList
      }
    },
    // ↓在methods里面
    getHeight() {
      this.tableConfig.height = window.innerHeight - 159
      console.log(this.tableConfig.height)
    },

    cancelForm() {
      this.loading = false
      this.open = false
    },
    confirmStop(row) {
      const data = {
        type: 'exec',
        mbean: row.WebMagic,
        operation: 'stop()'
      }
      updataState(data).then(res => {
        console.log(res)
        if (res.status === 200) {
          this.$message({ message: '停止成功', type: 'success' })
        }
      })
    },
    confirmStart(row) {
      const data = {
        type: 'read',
        mbean: row.WebMagic,
        config: { ignoreErrors: true }
      }

      updataState(data).then(res => {
        console.log(res)
        if (res.status === 200) {
          this.$message({ message: '启动成功', type: 'success' })
        }
      })
    },
    handleConfigQuery() {
      const data = {
        pageSize: 10,
        pageNum: 1,
        isAsc: 'asc',
        spiderCode: this.configForm.spiderCode,
        spiderName: this.configForm.spiderName
      }
      this.getConfigList(data)
    },
    toggleEdit() {
      this.openDataScope = true
    },
    /** 查询角色列表 */
    getList(value) {
      getState(this.queryParams).then(response => {
        if (response.value) {
          var arr = []
          for (const i in response.value) {
            response.value[i].WebMagic = i
            response.value[i].children = response.value[i].ErrorPages
            arr.push(response.value[i])
          }
          console.log(arr)
          this.roleList = arr
          this.loadMore()
        }
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false
      this.reset()
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([])
      }
      (this.menuExpand = false),
      (this.menuNodeAll = false),
      (this.deptExpand = true),
      (this.deptNodeAll = false),
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    resetConfigQuery() {
      const data = {
        pageSize: 10,
        pageNum: 1,
        isAsc: 'asc'
      }
      this.getConfigList(data)
      this.resetForm('configForm')
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.missionId)

      this.single = selection.length != 1
      this.multiple = !selection.length
    },

    handleConfigChange(selection) {
      if (selection.length > 0 && selection.length <= 1) {
        this.form.spiderName = selection[0].spiderName
        this.form.spiderConfigId = selection[0].id
      }
      this.selection = selection
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.open = true
      this.resetForm('form')
      this.form = {}
      this.title = '添加爬虫任务'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.open = true
      const exitWay =
        row.exitWay === 'DURATION'
          ? '持续时间'
          : row.exitWay === 'DEFAULT'
            ? '默认'
            : '链接计数'
      let spiderName = ''
      this.configList.map(item => {
        if (row.spiderConfigId === item.id) {
          return (spiderName = item.spiderName)
        }
      })
      this.form = {
        missionName: row.missionName,
        spiderConfigId: row.spiderConfigId,
        spiderName,
        exitWayCount: row.exitWayCount,
        exitWay,
        headerStr: row.headerStr,
        cookieStr: row.cookieStr,
        entryUrls: row.entryUrls,
        missionId: row.missionId
      }

      this.title = '修改爬虫任务'
    }
  }
}
</script>
<style scoped lang='scss'>
.demo-drawer__content {
  padding: 0 16%;
}
.config {
  ::v-deep .el-input__inner {
    background: #eee;
  }
}
::v-deep .el-popover__reference-wrapper {
  margin: 0 10px;
}
</style>
